<template>
  <div class="bg-gradient-to-b from-sky-50 to-white rounded-lg shadow-lg p-6 overflow-hidden relative">
    <!-- 背景装饰 -->
    <div class="absolute top-0 right-0 w-64 h-64 bg-indigo-100 rounded-full filter blur-3xl opacity-30 -translate-y-1/2 translate-x-1/3"></div>
    <div class="absolute bottom-0 left-0 w-80 h-80 bg-sky-100 rounded-full filter blur-3xl opacity-20 translate-y-1/3 -translate-x-1/3"></div>

    <!-- 标题区 -->
    <h2 class="text-xl font-semibold text-gray-800 mb-6 relative z-10 flex items-center">
      <span class="w-1 h-6 bg-gradient-to-b from-sky-500 to-indigo-600 rounded-full mr-3"></span>
      服务订单信息
    </h2>

    <!-- 搜索栏 -->
    <div class="flex flex-wrap items-center gap-4 mb-6 relative z-10">
      <!-- 订单状态搜索 -->
      <div class="flex items-center gap-2 flex-1 min-w-[240px]">
        <label class="text-sm font-medium text-gray-700 whitespace-nowrap">订单状态：</label>
        <input
            v-model="searchParams.status"
            placeholder="请填写订单状态"
            class="flex-1 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-sky-500 transition"
        >
      </div>

      <!-- 购买时间范围 -->
      <div class="flex items-center gap-2 flex-1 min-w-[320px]">
        <label class="text-sm font-medium text-gray-700 whitespace-nowrap">购买时间：</label>
        <input
            type="date"
            v-model="searchParams.startTime"
            class="flex-1 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-sky-500 transition"
        >
        <span class="text-gray-500 whitespace-nowrap">至</span>
        <input
            type="date"
            v-model="searchParams.endTime"
            class="flex-1 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-sky-500 transition"
        >
      </div>

      <!-- 查询按钮 -->
      <button
          @click="searchOrders"
          class="px-4 py-2 bg-sky-500 text-white rounded-md hover:bg-sky-600 transition transform hover:scale-105 active:scale-95"
      >
        查询
      </button>
    </div>

    <!-- 订单表格 -->
    <div class="overflow-x-auto relative z-10 rounded-lg border border-gray-200 shadow-sm">
      <table class="min-w-full divide-y divide-gray-200 bg-white">
        <thead class="bg-gray-50">
        <tr>
          <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider w-[80px]">编号</th>
          <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">订单编号</th>
          <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">合同模板</th>
          <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider w-[100px]">金额</th>
          <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">购买时间</th>
          <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">有效期至</th>
          <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider w-[100px]">状态</th>
          <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider w-[220px]">操作</th>
        </tr>
        </thead>
        <tbody class="bg-white divide-y divide-gray-200">
        <!-- 加载状态 -->
        <tr v-if="loading">
          <td colspan="8" class="px-4 py-12 text-center text-gray-500">
            <i class="fa fa-spinner fa-spin mr-2"></i>加载中...
          </td>
        </tr>

        <!-- 无数据状态 -->
        <tr v-else-if="filteredOrders.length === 0">
          <td colspan="8" class="px-4 py-12 text-center text-gray-500">
            <i class="fa fa-inbox mr-2 text-gray-300"></i>没有找到匹配的订单
          </td>
        </tr>

        <!-- 订单数据 -->
        <tr
            v-else
            v-for="(order, index) in paginatedOrders"
            :key="order.id || index"
            class="hover:bg-gray-50 transition-colors duration-150"
        >
          <td class="px-4 py-4 whitespace-nowrap text-sm text-gray-500">
            {{ (currentPage - 1) * pageSize + 1 + index || '未知编号' }}
          </td>
          <td class="px-4 py-4 whitespace-nowrap text-sm text-gray-500 font-medium">
            {{ order.id || '未知编号' }}
          </td>
          <td class="px-4 py-4 whitespace-nowrap text-sm text-gray-800">
            <div class="max-w-[180px] truncate" :title="order.templateName || '未命名合同'">
              {{ order.templateName || '未命名合同' }}
            </div>
          </td>
          <td class="px-4 py-4 whitespace-nowrap text-sm font-medium text-gray-800">
            ¥{{ typeof order.amount === 'number' ? order.amount.toFixed(2) : '0.00' }}
          </td>
          <td class="px-4 py-4 whitespace-nowrap text-sm text-gray-600">
            {{ formatDateTime(order.purchaseTime) }}
          </td>
          <td class="px-4 py-4 whitespace-nowrap text-sm text-gray-600">
            {{ formatDateTime(order.expiryDate) || '未设置' }}
          </td>
          <td class="px-4 py-4 whitespace-nowrap">
              <span :class="getStatusConfig(order.statusCode || 0).class">
                {{ getStatusConfig(order.statusCode || 0).text }}
              </span>
          </td>
          <!-- 操作列 -->
          <td class="px-4 py-4 whitespace-nowrap text-sm font-medium">
            <div class="flex flex-wrap items-center gap-2">
              <!-- 购买/下载按钮 -->
              <button
                  class="inline-flex items-center px-2.5 py-1.5 rounded text-sm text-blue-600 hover:bg-blue-50 transition-all duration-150 disabled:opacity-50 disabled:cursor-not-allowed"
                  @click="openPaymentModal(order)"
                  :disabled="!order.id || [4,5].includes(order.statusCode) || paymentLoading"
                  :title="getDownloadButtonTitle(order)"
              >
                <font-awesome-icon class="mr-1.5 text-xs" icon="download"/>
                <span>购买</span>
                <span v-if="paymentLoading && currentTradeNo === order.id" class="ml-1">
                  <i class="fa fa-spinner fa-spin text-xs"></i>
                </span>
              </button>

              <!-- 详情按钮 -->
              <button
                  class="inline-flex items-center px-2.5 py-1.5 rounded text-sm text-gray-600 hover:bg-gray-50 transition-all duration-150 disabled:opacity-50 disabled:cursor-not-allowed"
                  @click="handleAddOrder(order)"
                  :disabled="!order.id"
                  :title="!order.id ? '订单编号缺失，无法查看详情' : '查看详情'"
              >
                <font-awesome-icon icon="history" class="mr-1.5 text-xs" />
                <span>详情</span>
              </button>

              <!-- 取消按钮 -->
              <button
                  class="inline-flex items-center px-2.5 py-1.5 rounded text-sm text-red-600 hover:bg-red-50 transition-all duration-150 disabled:opacity-50 disabled:cursor-not-allowed"
                  @click="cancelOrder(order.id)"
                  :disabled="!order.id || !([1,2].includes(order.statusCode))"
                  :title="getCancelButtonTitle(order)"
              >
                <font-awesome-icon icon="times-circle" class="mr-1.5 text-xs" />
                <span>取消</span>
              </button>
            </div>
          </td>
        </tr>
        </tbody>
      </table>
    </div>

    <!-- 分页区 -->
    <div class="mt-6 flex flex-wrap justify-between items-center gap-4 relative z-10">
      <!-- 分页信息统计 -->
      <p class="text-sm text-gray-500">
        显示 {{ totalOrders > 0 ? (currentPage - 1) * pageSize + 1 : 0 }} 至
        {{ totalOrders > 0 ? Math.min(currentPage * pageSize, totalOrders) : 0 }} 条，
        共 {{ totalOrders }} 条记录
      </p>

      <!-- 分页控制按钮 -->
      <div class="flex items-center gap-1">
        <!-- 首页按钮 -->
        <button
            class="px-3 py-1.5 border border-gray-300 rounded hover:bg-gray-50 disabled:opacity-50 transition-colors text-sm"
            :disabled="currentPage === 1 || totalPages === 0"
            @click="changePage(1)"
        >
          <font-awesome-icon icon="chevron-left" class="mr-1 text-xs" />
          首页
        </button>

        <!-- 上一页按钮 -->
        <button
            class="px-3 py-1.5 border border-gray-300 rounded hover:bg-gray-50 disabled:opacity-50 transition-colors text-sm"
            :disabled="currentPage === 1 || totalPages === 0"
            @click="changePage(currentPage - 1)"
        >
          <font-awesome-icon icon="chevron-left" class="text-xs" />
        </button>

        <!-- 页码按钮组 -->
        <template v-for="(page, index) in visiblePages" :key="index">
          <span v-if="page === '...'" class="px-2 text-gray-500 text-sm">...</span>
          <button
              v-else
              class="px-3 py-1.5 border rounded transition-all text-sm min-w-[28px] text-center"
              :class="{
              'border-sky-500 bg-sky-50 text-sky-600': page === currentPage,
              'border-gray-300 hover:bg-gray-50': page !== currentPage
            }"
              @click="changePage(page)"
          >
            {{ page }}
          </button>
        </template>

        <!-- 下一页按钮 -->
        <button
            class="px-3 py-1.5 border border-gray-300 rounded hover:bg-gray-50 disabled:opacity-50 transition-colors text-sm"
            :disabled="currentPage >= totalPages || totalPages === 0"
            @click="changePage(currentPage + 1)"
        >
          <font-awesome-icon icon="chevron-right" class="text-xs" />
        </button>

        <!-- 末页按钮 -->
        <button
            class="px-3 py-1.5 border border-gray-300 rounded hover:bg-gray-50 disabled:opacity-50 transition-colors text-sm"
            :disabled="currentPage >= totalPages || totalPages === 0"
            @click="changePage(totalPages)"
        >
          末页
          <font-awesome-icon icon="chevron-right" class="ml-1 text-xs" />
        </button>
      </div>
    </div>

    <!-- 支付弹窗 -->
    <Teleport to="body">
      <div
          v-if="showPaymentModal"
          class="fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50 transition-opacity duration-200"
          @click="closePaymentModal"
      >
        <div
            class="bg-white rounded-lg shadow-xl w-full max-w-lg max-h-[85vh] flex flex-col transform transition-all duration-300 scale-95 opacity-0"
            @click.stop
            :class="showPaymentModal ? 'scale-100 opacity-100' : ''"
        >
          <div class="bg-gradient-to-r from-sky-500 to-indigo-600 text-white p-4 flex justify-between items-center">
            <h3 class="text-lg font-semibold">合同支付页面</h3>
            <button :disabled="paymentLoading" class="hover:text-white/80 transition-colors" @click="closePaymentModal">
              <font-awesome-icon icon="times"/>
            </button>
          </div>

          <div class="flex-1 p-6 overflow-y-auto space-y-6">
            <!-- 支付加载状态 -->
            <div v-if="paymentLoading" class="flex flex-col items-center justify-center py-10">
              <div class="inline-block animate-spin rounded-full h-10 w-10 border-b-2 border-sky-500 mb-4"></div>
              <p class="text-gray-600">处理中，请稍候...</p>
              <p class="text-gray-500 text-sm mt-2">正在获取支付信息或查询支付结果</p>
            </div>

            <div v-else>
              <div class="bg-gray-50 rounded-lg p-5">
                <h4 class="text-base font-medium text-gray-800 mb-4">订单信息</h4>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div class="space-y-1">
                    <label class="text-xs text-gray-500">订单编号</label>
                    <p class="text-sm text-gray-800 font-medium">{{ currentOrder.id || '未知编号' }}</p>
                  </div>
                  <div class="space-y-1">
                    <label class="text-xs text-gray-500">合同编号</label>
                    <p class="text-sm text-gray-800 font-medium">{{
                        currentOrder.contractNo || currentOrder.id || '未知编号'
                      }}</p>
                  </div>
                  <div class="space-y-1">
                    <label class="text-xs text-gray-500">合同名称</label>
                    <p class="text-sm text-gray-800">{{ currentOrder.templateName || '未命名合同' }}</p>
                  </div>
                  <div class="space-y-1">
                    <label class="text-xs text-gray-500">客户ID</label>
                    <p class="text-sm text-gray-800">{{ currentOrder.customerId }}</p>
                  </div>
                  <div class="space-y-1">
                    <label class="text-xs text-gray-500">需支付金额</label>
                    <p class="text-sm text-red-600 font-bold">
                      ¥{{ typeof currentOrder.amount === 'number' ? currentOrder.amount.toFixed(2) : '0.00' }}</p>
                  </div>
                  <div class="space-y-1">
                    <label class="text-xs text-gray-500">创建时间</label>
                    <p class="text-sm text-gray-800">{{ formatDateTime(currentOrder.purchaseTime) }}</p>
                  </div>
                  <div class="space-y-1">
                    <label class="text-xs text-gray-500">订单状态</label>
                    <p :class="getStatusConfig(currentOrder.statusCode || 0).textClass" class="text-sm">
                      {{ getStatusConfig(currentOrder.statusCode || 0).text }}
                    </p>
                  </div>
                  <!-- 支付结果反馈区域 -->
                  <div v-if="paymentResult" class="space-y-1">
                    <label class="text-xs text-gray-500">支付结果</label>
                    <p :class="paymentResult.success ? 'text-green-600' : 'text-red-600'" class="text-sm">
                      {{ paymentResult.message }}
                    </p>
                  </div>
                </div>
              </div>

              <!-- 表单处理错误提示 -->
              <div v-if="formSubmissionError" class="mt-4 p-3 bg-red-50 text-red-600 text-sm rounded">
                <i class="fa fa-exclamation-circle mr-1"></i>
                {{ formSubmissionError }}
              </div>

              <div class="space-y-4">
                <h4 class="text-base font-medium text-gray-800">选择支付方式</h4>
                <div
                    class="border border-gray-200 rounded-lg p-4 hover:border-sky-300 transition-colors cursor-pointer">
                  <div class="flex items-center justify-between">
                    <div class="flex items-center">
                      <i class="fab fa-alipay text-blue-500 text-2xl mr-3"></i>
                      <div>
                        <p class="text-sm font-medium text-gray-800">支付宝支付</p>
                        <p class="text-xs text-gray-500">推荐使用支付宝APP扫码支付</p>
                      </div>
                    </div>
                    <font-awesome-icon class="text-sky-500" icon="check-circle"/>
                  </div>
                </div>
              </div>

              <div class="pt-4 border-t border-gray-100">
                <button
                    :disabled="!currentOrder.id || currentOrder.statusCode !== 1 || paymentLoading"
                    class="w-full py-3 bg-gradient-to-r from-sky-500 to-indigo-600 text-white rounded-lg hover:from-sky-600 hover:to-indigo-700 transition-all shadow-sm hover:shadow flex items-center justify-center transform hover:scale-[1.02] active:scale-[0.98]"
                    @click="completePayment"
                >
                  <span v-if="paymentLoading"
                        class="inline-block animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></span>
                  {{
                    currentOrder.statusCode === 1 ? `立即支付 ¥${typeof currentOrder.amount === 'number' ? currentOrder.amount.toFixed(2) : '0.00'}` : getPaymentBtnText()
                  }}
                </button>
                <p class="text-xs text-gray-500 text-center mt-3">
                  支付后可立即下载合同，订单有效期至 {{ formatDateTime(currentOrder.expiryDate) || '未设置' }}
                </p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </Teleport>

    <!-- 自定义消息提示 -->
    <div
        v-if="showMessage"
        :class="[
          messageType === 'error' ? 'bg-red-50 text-red-500 border-red-100' :
          messageType === 'warning' ? 'bg-yellow-50 text-yellow-600 border-yellow-100' :
          'bg-green-50 text-green-500 border-green-100',
          'fixed top-4 right-4 p-4 rounded shadow-lg z-50 flex items-center border transition-all duration-300 transform translate-x-full opacity-0'
        ]"
        :style="showMessage ? 'translate-x-0 opacity-100' : ''"
    >
      <i :class="messageType === 'error' ? 'fa fa-exclamation-circle mr-2' :
                 messageType === 'warning' ? 'fa fa-exclamation-triangle mr-2' :
                 'fa fa-check-circle mr-2'"></i>
      <span>{{ messageText }}</span>
      <button @click="showMessage = false" class="ml-4 text-gray-400 hover:text-gray-600">
        <i class="fa fa-times"></i>
      </button>
    </div>
  </div>
</template>

<script>
import {
  getHistoryOrdersApi,
  getConditionOrdersApi,
  cancelOrderApi,
  queryPaymentResult
} from '@/api/orders'

export default {
  data() {
    return {
      // 分页相关
      currentPage: 1,
      pageSize: 10,
      totalOrders: 0,
      totalPages: 0,

      // 状态相关
      loading: false,
      showPaymentModal: false,
      paymentLoading: false,
      paymentTimer: null,
      currentTradeNo: '',
      paymentResult: null,
      formSubmissionError: null,
      tempFormElement: null,

      // 数据存储
      currentOrder: {},
      customerId: 'CUST2023001',
      filteredOrders: [],

      // 搜索条件
      searchParams: {
        status: '',
        startTime: '',
        endTime: ''
      },

      // 消息提示
      showMessage: false,
      messageText: '',
      messageType: 'success',

      // 订单状态配置
      statusConfig: {
        1: {
          text: '待付款',
          class: 'px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-yellow-100 text-yellow-800',
          textClass: 'text-yellow-600 font-medium'
        },
        2: {
          text: '已付款',
          class: 'px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800',
          textClass: 'text-green-600 font-medium'
        },
        3: {
          text: '已完成',
          class: 'px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-gray-100 text-gray-800',
          textClass: 'text-gray-600'
        },
        4: {
          text: '已取消',
          class: 'px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-red-100 text-red-800',
          textClass: 'text-red-600 font-medium'
        },
        5: {
          text: '已退款',
          class: 'px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-red-100 text-red-800',
          textClass: 'text-red-600 font-medium'
        }
      }
    }
  },

  computed: {
    // 分页后的订单数据
    paginatedOrders() {
      return this.filteredOrders.slice(
          0,
          10
      );
    },

    // 计算可见的页码
    visiblePages() {
      const pages = [];
      const maxVisible = 5;

      if (this.totalPages <= 1) {
        return [];
      }

      pages.push(1);

      if (this.currentPage > 3) {
        pages.push('...');
      }

      for (let i = Math.max(2, this.currentPage - 1); i <= Math.min(this.totalPages - 1, this.currentPage + 1); i++) {
        pages.push(i);
      }

      if (this.currentPage < this.totalPages - 2) {
        pages.push('...');
      }

      if (this.totalPages > 1) {
        pages.push(this.totalPages);
      }

      return pages;
    }
  },

  created() {
    this.fetchHistoryOrders();
  },

  beforeUnmount() {
    if (this.paymentTimer) {
      clearInterval(this.paymentTimer);
    }

    if (this.tempFormElement && this.tempFormElement.parentNode) {
      document.body.removeChild(this.tempFormElement);
    }
  },

  methods: {
    // 显示消息提示
    showMsg(text, type = 'success') {
      this.messageText = text;
      this.messageType = type;
      this.showMessage = true;

      setTimeout(() => {
        this.showMessage = false;
      }, 3000);
    },

    // 获取历史订单
    async fetchHistoryOrders() {
      this.loading = true;
      try {
        const response = await getHistoryOrdersApi(this.currentPage, this.pageSize);
        const backendData = response.data || {};
        let rawOrders = backendData.records || backendData.orders || [];

        this.filteredOrders = rawOrders.map(order => ({
          id: order.id || '',
          number: order.number || '',
          contractNo: order.contractNo || '',
          templateName: order.contractName || order.templateName || '未命名合同',
          amount: typeof order.payAmount === 'number' ? order.payAmount : 0,
          purchaseTime: order.createdTime || order.purchaseTime || '',
          expiryDate: order.expiryDate || this.calculateExpiryDate(order.createdTime),
          statusCode: typeof order.status === 'number' ? order.status : 0,
          customerId: order.customerId || this.customerId,
          contractType: order.contractType || ''
        }));

        this.totalOrders = backendData.total || this.filteredOrders.length;
        this.totalPages = Math.ceil(this.totalOrders / this.pageSize);
      } catch (error) {
        console.error('获取历史订单失败', error);
        this.filteredOrders = [];
        this.totalOrders = 0;
        this.totalPages = 0;
        this.showMsg('获取订单失败，请重试', 'error');
      } finally {
        this.loading = false;
      }
    },

    // 条件搜索订单
    async searchOrders() {
      this.currentPage = 1;
      this.loading = true;
      try {
        const searchCriteria = {
          startTime: this.searchParams.startTime ? `${this.searchParams.startTime} 00:00:00` : '',
          endTime: this.searchParams.endTime ? `${this.searchParams.endTime} 23:59:59` : '',
          page: this.currentPage,
          pageSize: this.pageSize,
          status: this.searchParams.status
        };

        const response = await getConditionOrdersApi(searchCriteria);
        const backendData = response.data || {};
        let rawOrders = backendData.records || backendData.list || [];

        this.filteredOrders = rawOrders.map(order => ({
          id: order.id || '',
          number: order.number || '',
          contractNo: order.contractNo || '',
          templateName: order.contractName || order.templateName || '未命名合同',
          amount: typeof order.payAmount === 'number' ? order.payAmount : 0,
          purchaseTime: order.createdTime || order.purchaseTime || '',
          expiryDate: order.expiryDate || this.calculateExpiryDate(order.createdTime),
          statusCode: typeof order.status === 'number' ? order.status : 0,
          customerId: order.customerId || this.customerId,
          contractType: order.contractType || ''
        }));

        this.totalOrders = backendData.total || this.filteredOrders.length;
        this.totalPages = Math.ceil(this.totalOrders / this.pageSize);
      } catch (error) {
        console.error('条件查询订单失败', error);
        this.filteredOrders = [];
        this.totalOrders = 0;
        this.totalPages = 0;
        this.showMsg('查询订单失败，请重试', 'error');
      } finally {
        this.loading = false;
      }
    },

    // 切换页码
    changePage(page) {
      if (page < 1 || page > this.totalPages) return;
      this.currentPage = page;

      if (this.searchParams.status || this.searchParams.startTime || this.searchParams.endTime) {
        this.searchOrders();
      } else {
        this.fetchHistoryOrders();
      }
    },

    // 计算有效期（创建时间+30天）
    calculateExpiryDate(createdTime) {
      if (!createdTime) return '';
      try {
        const date = new Date(createdTime);
        date.setDate(date.getDate() + 30);
        return date.toISOString().slice(0, 19).replace('T', ' ');
      } catch (error) {
        console.error('计算有效期失败', error);
        return '';
      }
    },

    // 获取订单状态配置
    getStatusConfig(statusCode) {
      return this.statusConfig[statusCode] || {
        text: '未知状态',
        class: 'px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-gray-100 text-gray-800',
        textClass: 'text-gray-600'
      };
    },

    // 格式化日期时间
    formatDateTime(timeStr) {
      if (!timeStr) return '未知时间';
      return timeStr.replace('T', ' ') || timeStr;
    },

    // 获取取消按钮标题
    getCancelButtonTitle(order) {
      if (!order.id) return '订单编号缺失，无法取消';
      if (![1, 2].includes(order.statusCode)) return '只有待付款/已付款订单可以取消';
      return '确认取消订单';
    },

    // 打开支付弹窗
    openPaymentModal(order) {
      if (!order?.id || [4, 5].includes(order.statusCode)) {
        this.showMsg('当前订单状态不支持支付操作', 'warning');
        return;
      }

      this.paymentResult = null;
      this.currentOrder = {...order};
      this.showPaymentModal = true;
    },

    // 按照支付宝支付示例思路修改的支付订单方法
    completePayment() {
      if (!this.currentOrder.id) {
        this.showMsg('订单信息错误，无法支付', 'error');
        return;
      }

      this.paymentLoading = true;
      this.formSubmissionError = null;
      this.showMsg('请求生成支付表单中...', 'success');

      // 构建支付参数
      const payParams = {
        userId: Number(this.currentOrder.customerId || this.customerId),
        amount: parseFloat(this.currentOrder.amount),
        orderId: this.currentOrder.id,
        subject: `购买-${this.currentOrder.templateName || '订单'}`
      };

      console.log('提交支付参数:', payParams);

      // 使用fetch替代原有请求方式，保持与示例一致
      fetch('http://localhost:8088/api/pay/zfb', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(payParams)
      })
          .then(response => {
            // 处理HTTP错误状态
            if (!response.ok) {
              throw new Error(`HTTP错误: ${response.status}`);
            }
            return response.json();
          })
          .then(result => {
            console.log('支付接口返回结果:', result);

            // 检查返回状态码，与示例保持一致
            if (result.code === 200) {
              this.showMsg('跳转支付宝支付中...', 'success');

              // 处理返回的表单数据
              if (!result.data || typeof result.data !== 'string') {
                throw new Error('后端返回的表单数据格式不正确');
              }

              // 提取交易号
              const tradeNoMatch = result.data.match(/out_trade_no&quot;:&quot;([^&]+)&quot;/);
              const tradeNo = tradeNoMatch ? tradeNoMatch[1] : `auto_${Date.now()}`;
              this.currentTradeNo = tradeNo;

              // 调用表单处理方法
              this.handleAlipay(result.data, tradeNo);
            } else {
              throw new Error(`生成支付表单失败：${result.message || '未知错误'}`);
            }
          })
          .catch(error => {
            this.paymentLoading = false;
            this.formSubmissionError = error.message;

            let errorMsg = '获取支付信息失败: ';
            if (error.message.includes('HTTP错误')) {
              errorMsg += '服务器连接错误，请检查服务是否可用';
            } else if (error.message.includes('Failed to fetch')) {
              errorMsg += '网络连接失败，请检查网络设置';
            } else {
              errorMsg += error.message;
            }

            this.showMsg(errorMsg, 'error');
            console.error('支付请求失败详情:', error);
          });
    },

    // 调整表单处理方法，与示例思路保持一致
    handleAlipay(payFormHtml, tradeNo) {
      this.formSubmissionError = null;

      try {
        // 创建临时容器
        const tempDiv = document.createElement('div');
        tempDiv.id = 'form-container';
        tempDiv.style.display = 'none';
        this.tempFormElement = tempDiv;
        document.body.appendChild(tempDiv);

        // 插入表单HTML，与示例一致
        tempDiv.innerHTML = payFormHtml;

        // 获取并提交表单
        const form = tempDiv.querySelector('form');
        if (!form) {
          throw new Error('未找到有效的支付表单');
        }

        // 验证表单地址
        this.validateFormUrl(form.action);

        // 隐藏表单并自动提交
        form.style.display = 'none';

        // 表单提交后的清理和查询
        const cleanupAndCheck = () => {
          if (this.tempFormElement && this.tempFormElement.parentNode) {
            document.body.removeChild(this.tempFormElement);
            this.tempFormElement = null;
          }
          this.startPaymentQueryTimer();
        };

        // 监听表单提交事件
        form.addEventListener('submit', cleanupAndCheck);

        // 执行提交
        form.submit();

      } catch (error) {
        this.formSubmissionError = error.message;
        this.showMsg(`支付处理失败: ${error.message}`, 'error');
        this.paymentLoading = false;

        // 清理临时元素
        if (this.tempFormElement && this.tempFormElement.parentNode) {
          document.body.removeChild(this.tempFormElement);
          this.tempFormElement = null;
        }
      }
    },

    // 新增表单地址验证方法
    validateFormUrl(actionUrl) {
      try {
        const url = new URL(actionUrl);
        const validDomains = ['alipay.com', 'alipaydev.com', 'alipayobjects.com'];
        const is_valid = validDomains.some(domain =>
            url.hostname.endsWith(domain)
        );

        if (!is_valid) {
          throw new Error(`支付地址不合法: ${url.hostname}`);
        }
      } catch (error) {
        throw new Error(`表单地址无效: ${error.message}`);
      }
    },

    // 支付结果查询定时器
    startPaymentQueryTimer() {
      if (this.paymentTimer) clearInterval(this.paymentTimer);

      let checkCount = 0;
      const maxChecks = 30;

      this.paymentTimer = setInterval(async () => {
        checkCount++;

        if (checkCount >= maxChecks) {
          clearInterval(this.paymentTimer);
          this.paymentLoading = false;
          this.paymentResult = {
            success: false,
            message: '支付超时，请手动查看订单状态'
          };
          return;
        }

        try {
          const result = await queryPaymentResult({
            tradeNo: this.currentTradeNo,
            orderId: this.currentOrder.id
          });

          if (result.data?.paid) {
            clearInterval(this.paymentTimer);
            this.paymentLoading = false;
            this.paymentResult = {
              success: true,
              message: '支付成功，订单已更新'
            };
            this.showMsg('支付成功！', 'success');

            setTimeout(() => {
              this.fetchHistoryOrders();
              this.closePaymentModal();
            }, 1000);
          }
        } catch (error) {
          console.error(`第${checkCount}次支付查询失败:`, error);

          if (checkCount === 10) {
            this.showMsg('支付状态查询延迟，请耐心等待', 'warning');
          }
        }
      }, 3000);
    },

    // 获取下载按钮标题
    getDownloadButtonTitle(order) {
      if (!order.id) return '订单信息不完整';
      if ([4, 5].includes(order.statusCode)) return '订单已取消或退款，无法购买';
      if ([2, 3].includes(order.statusCode)) return '已支付，点击下载';
      return '点击购买';
    },

    // 关闭支付弹窗
    closePaymentModal() {
      this.showPaymentModal = false;
      this.currentOrder = {};

      if (this.paymentTimer) {
        clearInterval(this.paymentTimer);
        this.paymentTimer = null;
      }

      if (this.tempFormElement && this.tempFormElement.parentNode) {
        document.body.removeChild(this.tempFormElement);
        this.tempFormElement = null;
      }
    },

    // 支付按钮文本
    getPaymentBtnText() {
      const textMap = {
        2: '已支付完成',
        3: '订单已完成',
        4: '订单已取消',
        5: '订单已退款'
      };
      return textMap[this.currentOrder.statusCode] || '无法支付';
    },

    // 显示订单详情
    async showOrderDetail(order) {
      this.$router.push({
        path: 'orders/add',
        query: {
          order: order.id,
        }
      });
    },

    // 新增订单处理方法
    handleAddOrder(order) {
      const newOrder = {
        number: order.number || '',
        contractNo: order.contractNo || '',
        templateName: order.templateName || order.templateName || '未命名合同',
        amount: typeof order.amount === 'number' ? order.amount : 0,
        expiryDate: order.expiryDate || this.calculateExpiryDate(order.createdTime),
        statusCode: typeof order.status === 'number' ? order.status : 0,
        customerId: order.customerId || this.customerId,
        contractType: order.contractType || ''
      };

      try {
        const serializedOrder = JSON.stringify(newOrder);
        this.$router.push({
          path: 'orders/add',
          query: {
            order: serializedOrder,
            mode: 'add',
            t: new Date().getTime()
          }
        });
      } catch (error) {
        console.error('创建新订单失败:', error);
        this.showMsg('创建新订单失败，请重试', 'error');
      }
    },

    // 取消订单
    async cancelOrder(orderId) {
      if (!orderId || !confirm('确定要取消此订单吗？')) return;

      this.loading = true;
      try {
        await cancelOrderApi(orderId);
        this.showMsg('订单已取消');
        this.fetchHistoryOrders();
      } catch (error) {
        console.error('取消订单失败', error);
        this.showMsg('取消订单失败，请重试', 'error');
      } finally {
        this.loading = false;
      }
    }
  }
}
</script>

<!-- 引入外部资源 -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
